package com.net.xpay.web.controller.merchant.auto;


import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.net.xpay.web.vo.AutoPayOrderExportVo;
import com.net.xpay.web.vo.AutoPayOrderVo;
import com.net.common.exception.BusinessException;
import com.net.common.model.ResultData;
import com.net.common.model.ResultPagedList;
import com.net.common.util.LocalDateUtil;
import com.net.common.util.SerializationUtil;
import com.net.xpay.alipay.enums.IdentityType;
import com.net.xpay.common.domain.User;
import com.net.xpay.core.constant.PoseidonErrorCode;
import com.net.xpay.core.domain.auto.AutoPayOrder;
import com.net.xpay.core.manager.auto.AutoPayOrderManager;
import com.net.xpay.core.model.AutoPayOrderSearchModel;
import com.net.xpay.core.utils.BeanCopierUtil;
import com.net.xpay.core.utils.JxlsUtils;
import com.net.xpay.web.secutiry.RequestUser;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Slf4j
@RequestMapping("/merchant/auto-pay-order")
@Api(tags = "商户/自动打款收款名单", description = "商户 自动打款收款名单 net")
public class AutoPayOrderController {


    @Autowired
    private AutoPayOrderManager autoPayOrderManager;


    /**
     * 搜索
     */
    @ApiOperation("搜索")
    @PostMapping("/search")
    public ResultPagedList<AutoPayOrderVo> searchPayTrans(@ApiIgnore @RequestUser User merchant, @RequestBody AutoPayOrderSearchModel searchModel) {
        Preconditions.checkArgument(searchModel != null);
        searchModel.setUserId(merchant.getId());

        List<AutoPayOrder> records = autoPayOrderManager.search(searchModel);
        List<AutoPayOrderVo> vos = BeanCopierUtil.batchCopy(AutoPayOrder.class, AutoPayOrderVo.class, records);
        long count = autoPayOrderManager.searchCount(searchModel);

        return new ResultPagedList<>(vos, count, searchModel);
    }

    /**
     * 待转账金额统计
     */
    @ApiOperation("待转账金额统计")
    @PostMapping("/sum-ensured-amount")
    public ResultData<BigDecimal> sumEnsuredAmount(@ApiIgnore @RequestUser User merchant) {
        return new ResultData<>(autoPayOrderManager.sumEnsuredAmount(merchant.getId()));
    }

    /**
     * 导出单笔明细
     */
    @ApiOperation("导出单笔明细")
    @GetMapping("/export-detail")
    public ResultData<Boolean> exportAutoPayTransDetail(@ApiIgnore HttpServletRequest request, @ApiIgnore HttpServletResponse response, @ApiIgnore @RequestUser User merchant, String searchModelJson) {
        Preconditions.checkArgument(searchModelJson != null);
        AutoPayOrderSearchModel searchModel = SerializationUtil.str2Object(searchModelJson, AutoPayOrderSearchModel.class);
        searchModel.setUserId(merchant.getId());
        long totalCount = autoPayOrderManager.searchCount(searchModel);
        if (totalCount > 10000L) {
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "导出明细超过1万条，无法导出");
        }
        List<AutoPayOrder> autopayTransList = autoPayOrderManager.list(searchModel);

        // 定义一个Map，往里面放入要在模板中显示数据
        Map<String, Object> model = new HashMap<>();
        List<AutoPayOrderExportVo> vos = BeanCopierUtil.batchCopy(AutoPayOrder.class, AutoPayOrderExportVo.class, autopayTransList);
        vos.forEach(vo -> {
            if (IdentityType.ALIPAY_LOGON_ID.getValue().equals(vo.getIdentityType()))  {
                vo.setAccountType("支付宝账号");
            } else {
                vo.setAccountType("淘宝昵称");
            }

            vo.setDate(LocalDateUtil.getDateTimeAsString(vo.getCreateTime()));
        });
        model.put("autoPayOrder", vos);

        String fileName = "鱼塘打款明细.xlsx";
        String template = "/excel/tpl/鱼塘打款明细.xls";

        InputStream is;
        try {
            //获取模板流
            is = getClass().getResourceAsStream(template);

            //火狐游览器中文文件名会有乱码,兼容火狐
            String agent = request.getHeader("USER-AGENT").toLowerCase();

            if (!Strings.isNullOrEmpty(agent) && (agent.contains("firefox") || agent.contains("safari"))) {
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            } else {
                fileName = URLEncoder.encode(fileName, "UTF-8");
            }
            response.setContentType("application/force-download");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            JxlsUtils.exportExcel(is, response.getOutputStream(), model);
            response.flushBuffer();
        } catch (IOException e) {
            log.warn("export error", e);
        }
        return new ResultData<>();
    }

}
